<template>
  <div class="mod-config">
    <div v-if="!addOrUpdateVisible">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input v-model="dataForm.key" placeholder=转换器名称 clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
          <el-button  type="primary" @click="addOrUpdateHandle()">新增</el-button>
          <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="name"
          header-align="center"
          align="center"
          label="转换器名称">
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="fromtypeString"
          header-align="center"
          align="center"
          label="from操作类型">
        </el-table-column>
        <el-table-column
          prop="providerxml"
          header-align="center"
          align="center"
          :show-overflow-tooltip="true"
          label="获取规则
">
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="totypeString"
          header-align="center"
          align="center"
          label="to操作类型
">
        </el-table-column>
        <el-table-column
          prop="receiversxml"
          header-align="center"
          align="center"
          :show-overflow-tooltip="true"
          label="转储规则
">
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="addTime"
          header-align="center"
          align="center"
          label="创建时间
">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row,scope.index)"
              v-hasPermi="['monitor:operlog:query']"
            >详细</el-button>
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row.id,scope.row.name)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[8, 15, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <!-- 操作日志详细 -->
      <el-dialog title="转换器详细" :visible.sync="open" width="1000px"  append-to-body>
        <el-form ref="form" style="max-height:350px;overflow: auto;" :model="form" label-width="100px" size="mini">
          <el-row>
            <el-col :span="8">
              <!--<el-form-item label="任务id：">{{ form.id }}</el-form-item>-->
              <el-form-item
                label="名称："
              >{{ form.name }}</el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="获取类型：">{{ form.fromtypeString }}</el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="存储类型：">
                {{form.totypeString}}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="获取规则：">
                <!--{{ form.receiversxml }}-->
                <xmp><div >{{ form.providerxml }}</div></xmp>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="存储规则：">
                <!--  {{ form.providerxml }}-->
                <xmp><div >{{ form.receiversxml }}</div></xmp>
              </el-form-item>
            </el-col>



          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @handleClose="handleClose" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './ssbustranslator-add-or-update'
export default {
  data () {
    return {
      open: false,
      form:{},
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 8,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate
  },
  activated () {
    this.getDataList()
  },
  create(){
    this.getDataList();
    this.addOrUpdateVisible=true
  },
  methods: {
    showXml(str){
      var text = str
      var item=this;

      //去掉多余的空格
      text = '\n' + text.replace(/(<\w+)(\s.*?>)/g,function($0, name, props)
      {
        return name + ' ' + props.replace(/\s+(\w+=)/g," $1");
      }).replace(/>\s*?</g,">\n<");

      //把注释编码
      text = text.replace(/\n/g,'\r').replace(/<!--(.+?)-->/g,function($0, text)
      {
        var ret = '<!--' + escape(text) + '-->';
        return ret;
      }).replace(/\r/g,'\n');

      //调整格式
      var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
      var nodeStack = [];
      var output = text.replace(rgx,function($0,all,name,isBegin,isCloseFull1,isCloseFull2 ,isFull1,isFull2){
        var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/' ) || (isFull1 == '/') || (isFull2 == '/');
        var prefix = '';
        if(isBegin == '!')
        {
          prefix = item.getPrefix(nodeStack.length);
        }
        else
        {
          if(isBegin != '/')
          {
            prefix = item.getPrefix(nodeStack.length);
            if(!isClosed)
            {
              nodeStack.push(name);
            }
          }
          else
          {
            nodeStack.pop();
            prefix = item.getPrefix(nodeStack.length);
          }

        }
        var ret =  '\n' + prefix + all;
        return ret;
      });

      var prefixSpace = -1;
      var outputText = output.substring(1);

      //把注释还原并解码，调格式
      outputText = outputText.replace(/\n/g,'\r').replace(/(\s*)<!--(.+?)-->/g,function($0, prefix,  text)
      {
        if(prefix.charAt(0) == '\r')
          prefix = prefix.substring(1);
        text = unescape(text).replace(/\r/g,'\n');
        var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix ) + '-->';
        return ret;
      });
      //alert(outputText);

      outputText=	outputText.replace(/\s+$/g,'').replace(/\r/g,'\r\n');


      return outputText


    },
    getPrefix(prefixIndex) {
      var span = '    ';
      var output = [];
      for(var i = 0 ; i < prefixIndex; ++i)
      {
        output.push(span);
      }

      return output.join('');
    },

    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form=row
      this.form.receiversxml=this.showXml(row.receiversxml);
      this.form.providerxml=this.showXml(row.providerxml);

    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = false
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/tbssbustranslator/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'key': this.dataForm.key
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    //获取子组件传递过来的值
    handleClose(data){
      this.addOrUpdateVisible = data;
      this.getDataList();
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },

    // 删除
    deleteHandle (id,name) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      var names = name
        ? [name]
        : this.dataListSelections.map((item) => {
          return item.name;
        });
      /*    this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {*/
      this.$confirm(`确定对[名称=${names.join(",")}]进行[${name ? "删除" : "批量删除"}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/tbssbustranslator/deletes'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
